package com.it.system.searchservice.listener;

import com.alibaba.fastjson.JSON;
import com.it.system.educommonapi.entity.Course;
import com.it.system.searchservice.service.CourseIndexService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class CourseMQListener {

    public static final String QUEUE_UPDATE = "course-update-queue";
    public static final String QUEUE_DELETE = "course-delete-queue";
    public static final String EXCHANGE_COURSE = "course-exchange";
    public static final String KEY_UPDATE = "course-update-key";
    public static final String KEY_DELETE = "course-delete-key";

    @Autowired
    private CourseIndexService courseIndexService;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = QUEUE_UPDATE, durable = "true"),
                    exchange = @Exchange(
                            value = EXCHANGE_COURSE,
                            type = ExchangeTypes.TOPIC,
                            ignoreDeclarationExceptions = "true"
                    ),
                    key = KEY_UPDATE
            )
    })
    public void listenCourseUpdate(String courseJson) {
        try {
            log.info("收到课程更新消息：{}", courseJson);
            Course course = JSON.parseObject(courseJson, Course.class);
            courseIndexService.saveCourse(course);
            log.info("课程索引更新成功：{}", course.getId());
        } catch (Exception e) {
            log.error("处理课程更新消息失败：{}", e.getMessage(), e);
        }
    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = QUEUE_DELETE, durable = "true"),
                    exchange = @Exchange(
                            value = EXCHANGE_COURSE,
                            type = ExchangeTypes.TOPIC,
                            ignoreDeclarationExceptions = "true"
                    ),
                    key = KEY_DELETE
            )
    })
    public void listenCourseDelete(String courseId) {
        try {
            log.info("收到课程删除消息，课程ID：{}", courseId);
            courseIndexService.removeCourse(courseId);
            log.info("课程索引删除成功：{}", courseId);
        } catch (Exception e) {
            log.error("处理课程删除消息失败：{}", e.getMessage(), e);
        }
    }
}